package com.ug.logs.ascept;

import com.ug.common.constant.CommonConstants;
import com.ug.common.utils.*;
import com.ug.system.entity.SysOperLog;
import com.ug.system.service.SysOperLogService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author LY
 * @create 2024/7/16 17:41
 * @Description 操作日志切面
 */
@Slf4j
@Aspect
@Component
public class LogAspect {

    private final SysOperLogService sysOperLogService;

    ThreadLocal<Long> currentTime = new ThreadLocal<>();

    public LogAspect(SysOperLogService sysOperLogService){
        this.sysOperLogService = sysOperLogService;
    }

    /**
     * 配置切入点
     */
    @Pointcut("@annotation(com.ug.logs.annotation.Log)")
    public void logPointcut(){

    }

    /**
     * 配置环绕通知,使用在方法logPointcut()上注册的切入点
     */
    @Around("logPointcut()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        currentTime.set(System.currentTimeMillis());
        //  执行通知方法
        result = joinPoint.proceed();
        SysOperLog sysOperLog = new SysOperLog(CommonConstants.LOG_SUCCESS, System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        sysOperLogService.save(getUsername(), joinPoint, sysOperLog);
        return result;
    }

    /**
     * 配置异常通知
     */
    @AfterThrowing(pointcut = "logPointcut()", throwing = "e")
    @Transactional(rollbackFor = Exception.class)
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e){
        SysOperLog sysOperLog = new SysOperLog(CommonConstants.LOG_ERROR,System.currentTimeMillis() - currentTime.get());
        currentTime.remove();
        sysOperLog.setExceptionDetail(ThrowsUtil.getStackTrace(e));
        sysOperLogService.save(getUsername(), (ProceedingJoinPoint)joinPoint, sysOperLog);
    }

    /**
     * 获取当前登录用户名
     */
    public String getUsername() {
        try {
            return SecurityUtil.getCurrentUsername();
        }catch (Exception e){
            return "";
        }
    }
}
